<?php
    /*
    TODO:
    AJAX更新列表
    AJAX发送控制
    前后端分离，后端：php/c#/其他
    ES6代码（Object, =>）处理/webpack打包

    ?do=send/set/get/list&id=xxx&send=yyy&back=zzz

    如果有Get请求，则返回控制
    如果无Get请求，则显示状态

    ID: 客户端ID
    Send: 客户端发送信息，用于发送状态，显示为指示灯
    Back: 服务器返回信息，用于返回控制，显示为开关

    数据格式：0123456789ABCDEF，长度可变，低位在右，高位在左

    数据协议：
    位  0(Send) 0(Back) 1(Send) 1(Back)
    0   在线    -       上线    关机
    1   在线    -       下线    重启
    */

    // header("Access-Control-Allow-Origin: *");
    // header("Content-Type: application/json; charset=UTF-8");
    
    $data_file = "index.json";
    date_default_timezone_set("Asia/Shanghai");
    error_reporting(0);

    if($_GET)
    {
        if(file_exists($data_file))
        {
            // 读取数据
            $data_json = file_get_contents($data_file);
            $data = json_decode($data_json, true);
        }
        if(isset($_GET["get"]))
        {
            echo($data_json);
        }
        else if(isset($_GET["id"]))
        {
            // 获取ID
            $id = $_GET["id"];

            // 返回控制
            if(isset($data[$id]["back"])) echo($data[$id]["back"]);

            // TODO: 关机重启控制信息返回后清除
        }
        if(isset($_GET["id"]))
        {
            // 获取ID
            $id = $_GET["id"];

            // 修改数据
            if(isset($_GET["send"]))
            {
                $data[$id]["ip"] = $_SERVER["REMOTE_ADDR"];
                $data[$id]["send"] = $_GET["send"];
                $data[$id]["stime"] = time();
            }
            if(isset($_GET["back"]))
            {
                $data[$id]["back"] = $_GET["back"];
                $data[$id]["btime"] = time();
            }

            // 写入数据
            $data_json = json_encode($data);
            file_put_contents($data_file, $data_json);
        }
    }
    else
    {
?>

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Secure Remote Control</title>
    <!-- WebApp全屏模式 -->
    <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no, minimal-ui">
    <!-- 隐藏状态栏/设置状态栏颜色 -->
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <!-- safri 添加到主屏界面的显示标题 -->
    <meta name="apple-mobile-web-app-title" content="远程控制">
    <!-- <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" /> -->
    <!-- uc强制竖屏 -->
    <meta name="screen-orientation" content="portrait">
    <!-- UC强制全屏 --> 
    <meta name="full-screen" content="yes">
    <!-- UC应用模式 --> 
    <meta name="browsermode" content="application">
    <!-- QQ强制竖屏 -->
    <meta name="x5-orientation" content="portrait">
    <!-- QQ强制全屏 -->
    <meta name="x5-fullscreen" content="true">
    <!-- QQ应用模式 -->
    <meta name="x5-page-mode" content="app">
    <!-- 是针对一些老的不识别viewport的浏览器，列如黑莓 -->
    <meta name="HandheldFriendly" content="true">
    <!-- 微软的老式浏览器 -->
    <meta name="MobileOptimized" content="320">
    <!-- <meta http-equiv="refresh" content="2"> -->
    <link rel="stylesheet" href="w3css/w3.css">
    <link rel="stylesheet" href="w3css/w3-theme-deep-purple.css">
    <script src="w3css/w3.js"></script>
</head>
<body class="w3-theme-l5 w3-text-theme w3-border-theme" onload="refresh()">
    <nav class="w3-sidebar w3-bar-block w3-card" id="mySidebar">
        <div class="w3-container w3-xlarge w3-theme-d2">
            <div class="w3-center w3-padding">菜单</div>
            <span class="w3-button w3-display-topright" onclick="closeSidebar()">X</span>
        </div>
        <a class="w3-bar-item w3-button w3-disabled" href="#">主页</a>
        <a class="w3-bar-item w3-button w3-disabled" href="#">朋友圈</a>
        <a class="w3-bar-item w3-button w3-disabled" href="#">消息</a>
    </nav>

    <header class="w3-bar w3-xlarge w3-top w3-theme">
        <button class="w3-bar-item w3-button w3-hover-theme" onclick="openSidebar()">&#9776;</button>
        <div class="w3-bar-item">安全远程控制</div>
    </header>

    <div style="margin-top:52px">
        <ul id="idData" class="w3-ul w3-hoverable" style="display: none">
            <?php/*
                if(file_exists($data_file))
                {
                    // 读取数据
                    $data_json = file_get_contents($data_file);
                    $data = json_decode($data_json, true);

                    // 显示数据
                    foreach($data as $key = $value)
                    {
            */?>
            <!-- <li w3-repeat="array" class="w3-border w3-margin" style="padding:0px">
                <div class="w3-container w3-display-container w3-theme-l4"><h4><?=$key?></h4>
                    <div class="w3-display-right w3-margin-right">
                        <button class="w3-button <?=$value['back']==1?'w3-theme-dark':'w3-theme-light'?>" onclick="set('<?=$key?>', 1)">关机</button>
                        <button class="w3-button <?=$value['back']==2?'w3-theme-dark':'w3-theme-light'?>" onclick="set('<?=$key?>', 2)">重启</button>
                    </div>
                </div>
                <ul class="w3-ul">
                    <li><span class="w3-tag w3-theme">IP</span>: <?=$value["ip"]?></li>
                    <li><span class="w3-tag w3-theme">Send <span class="w3-opacity"><?=$value["stime"]?date("(Y-m-d H:i:s)", $value["stime"]):null?></span></span>: <?=$value["send"]?></li>
                    <li><span class="w3-tag w3-theme">Back <span class="w3-opacity"><?=$value["btime"]?date("(Y-m-d H:i:s)", $value["btime"]):null?></span></span>: <?=$value["back"]?></li>
                </ul>
            </li> -->
            <?php/*
                    }
                }
            */?>

            <li w3-repeat="array" class="w3-border w3-margin" style="padding:0px">
                <div class="w3-container w3-display-container w3-theme-l4"><h4>{{id}}</h4>
                    <div class="w3-display-right w3-margin-right">
                        <button class="w3-button {{classShutdown}}" onclick="set('{{id}}', 1)">关机</button>
                        <button class="w3-button {{classReboot}}" onclick="set('{{id}}', 2)">重启</button>
                    </div>
                </div>
                <ul class="w3-ul">
                    <li><span class="">IP</span>: {{ip}}</li>
                    <li><span class="">Send <span class="w3-opacity">{{stime}}</span></span>: <pre>{{send}}</pre></li>
                    <li><span class="">Back <span class="w3-opacity">{{btime}}</span></span>: <pre>{{back}}</pre></li>
                </ul>
            </li>
        </ul>

        <div id="time" class="w3-small w3-center w3-opacity" style="padding-bottom:48px">
            {{data}}<br>
            Copyright by <a href="https://gitee.com/idengwei">dengwei</a>.<br>
            Powered by <a href="w3css/w3css_references.html">W3.CSS</a> <a href="w3css/w3js_references.html">W3.JSS</a>.
        </div>
    </div>

    <footer class="w3-bar w3-large w3-bottom w3-theme">
        <div class="w3-bar-item w3-opacity-min">Secure Remote Control</div>
    </footer>

    <script>
        closeSidebar();
        function openSidebar() {
            document.getElementById("mySidebar").style.display = "block";
        }

        function closeSidebar() {
            document.getElementById("mySidebar").style.display = "none";
        }

        function list() {
            //
            w3.getHttpObject("https://7npmedia.w3cschool.cn/customers1.js", myFunction);
            function myFunction(myObject) {
                w3.displayObject("id01", myObject);
            }
        }

        function set(id, back) {
            w3.getHttpObject('?id='+id+'&back='+back, get);
        }

        function update(data) {
            console.log(data);
            data = Object.entries(data).map(item=>({
                id: item[0],
                ip: item[1].ip||'',
                classShutdown: item[1].back==1 ? 'w3-theme-dark':'w3-theme-light',
                classReboot: item[1].back==2 ? 'w3-theme-dark':'w3-theme-light',
                stime: new Date(item[1].stime*1000).toLocaleString()||'',
                btime: new Date(item[1].btime*1000).toLocaleString()||'',
                send: item[1].send||'',
                back: item[1].back||'',
            }));
            console.log(data);
            w3.displayObject("idData", {array:data});
            w3.displayObject("time", {data: new Date()});
            // w3.displayObject("idData", {data: data});
            w3.show("#idData");
        }

        function get() {
            w3.getHttpObject('?get', update);
        }

        function refresh() {
            // 2秒自动刷新
            w3.hide("#idData");
            get();
            timer = window.setInterval(get, 10000);
        }
    </script>

<!-- 
    <table>
        <tr>
            <td>ID</td>
            <td>Send</td>
            <td>Back</td>
            <td>Send Time</td>
            <td>Back Time</td>
        </tr>
    </table>
    <br />

    <table>
        <tr>
            <td>ID</td>
            <td>IP</td>
            <td>在线</td>
            <td>操作</td>
        </tr>
        <tr>
            <td>dengwei-pc</td>
            <td>2409:8a20:c28:c400:1422:cca2:d585:586e</td>
            <td>1s 前</td>
            <td>访问, 关机, 睡眠</td>
        </tr>
    </table>
    <br />

    <table>
        <tr>
            <td>
                <pre><?php/*
                    echo("_SERVER: "); print_r($_SERVER); echo("\n");
                    echo("_ENV: "); print_r($_ENV); echo("\n");
                    echo("_FILES: "); print_r($_FILES); echo("\n");
                    echo("_GET: "); print_r($_GET); echo("\n");
                    echo("_POST: "); print_r($_POST); echo("\n");
                    echo("_REQUEST: "); print_r($_REQUEST); echo("\n");
                    echo("_COOKIE: "); print_r($_COOKIE); echo("\n");
                    echo("_SESSION: "); print_r($_SESSION); echo("\n");
                */?></pre>
            </td>
        </tr>
    </table>
    <br />

    <?php/*
        phpinfo();
    */?>
-->
</body>
</html>

<?php
    }
?>
